package com.pj.viewpager;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.pj.viewpager.adapter.MyFragmentPagerAdapter;
import com.pj.viewpager.fragment.NewsListFragment;

import java.util.ArrayList;
import java.util.List;

public class FragmentAndViewPager extends AppCompatActivity {

    private ViewPager fragmentAndViewPager;
    private List<Fragment> fragments;
    private TabLayout tab;
    private String[] title = {"新闻","美食","运动","医疗","游戏"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_and_view_pager);
        initView();
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, fragments,title);
        fragmentAndViewPager.setAdapter(adapter);
        tab.setupWithViewPager(fragmentAndViewPager);
    }

    private void initView() {
        fragmentAndViewPager = (ViewPager) findViewById(R.id.fragment_and_view_pager);
        fragments = new ArrayList<>();
        fragments.add(new NewsListFragment(title[0]));
        fragments.add(new NewsListFragment(title[1]));
        fragments.add(new NewsListFragment(title[2]));
        fragments.add(new NewsListFragment(title[3]));
        fragments.add(new NewsListFragment(title[4]));
        tab = (TabLayout) findViewById(R.id.tab);
    }
}